<template>
  <div id="quill">
    <el-form ref="newEditForm" size="mini" :model.sync="newEditForm">
      <el-form-item label="商品主图" :label-width="formLabelWidth">

        <div style="display: flex;">
            <div class="imgBox" @click="newEditForm.imageDetail.splice(index, 1)" v-for="(item,index) in newEditForm.imageDetail" :key="item">
                <el-image
                    style="width: 50px;height: 50px;"
                    :src="imgPrefix+item"
                    fit="scale-down"
                    @click.native="uploadClick"
                ></el-image>
                <div class="imgLight el-icon-close"></div>
            </div>
            <!-- 添加图片按钮 -->
            <div v-if="newEditForm.imageDetail.length<5" class="icon-wrap" @click="uploadClick">
                <i class="el-icon-circle-plus-outline"></i>
            </div>
        </div>
        

        <el-upload
          ref="iconUpload"
          with-credentials
          :action="serverUrl"
          style="display: none"
          accept="image/*"
          :headers="uploadHeaders"
          :on-change="handleUploadChange"
        >
          <el-button size="small" id="uploadImg" ref="uploadImg">点击上传</el-button>
        </el-upload>
        <p>限定上传5张图片，建议尺寸：800*800像素</p>
      </el-form-item>
      <el-form-item label="商品描述" :label-width="formLabelWidth">
        <ul class="selectWeb">
            <li :class="curMode === 'pc' ? 'selectNav' : ''" @click="curMode = 'pc'">PC端</li>
            <li :class="curMode !== 'pc' ? 'selectNav' : ''" @click="curMode = 'mobile'">移动端</li>
        </ul>
        <span v-html="style"></span>
        <!-- 图片上传组件辅助-->
        <el-upload
          class="avatar-uploader"
          :action="serverUrl"
          :data="uploadImgData"
          accept="image/*"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :headers="uploadHeaders"
          :before-upload="beforeUpload"
        ></el-upload>

        <quill-editor
          v-model="curContent"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
          style="height:400px;"
        ></quill-editor>

        <div style="text-align: center; margin-top: 95px;">
          <el-button size="mini" type="primary" @click="back">上一步</el-button>
          <el-button size="mini" type="primary" @click="submit">提交</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";

import { baseUrl } from "@/config/env";
import { getToken } from "@/utils/auth";

const uploadUrl = baseUrl + "/rest/common/upload";

//获取图片的url
const imgPrefix = baseUrl + "/rest/common/preview/";

// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["link", "image"] // 链接、图片、视频
];

export default {
  data() {
    return {
        style: `
            <style>
                #quill .avatar-uploader {
                    display: none;
                }
            </style>
        `,
        curMode: 'pc',
      curContent: '',
      editorOption: {
        placeholder: "编辑文章内容"
      },
      //token头信息
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      //图片上传的参数
      uploadImgData: { form: "detail" },
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      editorOption: {
        placeholder: "",
        theme: "snow", // or 'bubble'
        placeholder: "请输入内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            // container: "#toolbar",
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              }
              // link: function(value) {
              //   if (value) {
              //     var href = prompt('请输入url');
              //     this.quill.format("link", href);
              //   } else {
              //     this.quill.format("link", false);
              //   }
              // },
            }
          }
        }
      },
      serverUrl: uploadUrl, // 这里写你要上传的图片服务器地址
      newEditForm: {
          imageDetail: [],
          mobileDesc: '',
          metaDesc: ''
      },
      imgPrefix: imgPrefix,
      formLabelWidth: "100px"
    };
  },
  props: ['newEditFormThree'],
  created () {
    this.newEditForm = JSON.parse(JSON.stringify(this.newEditFormThree))
    this.curContent = this.newEditForm.metaDesc;
  },
  components: {
    quillEditor
  },
  watch: {
      curContent (cur) {
          this.curMode === 'pc' ? this.newEditForm.metaDesc = cur : this.newEditForm.mobileDesc = cur;
      },
      curMode (cur) {
          this.curContent = cur === 'pc' ? this.newEditForm.metaDesc : this.newEditForm.mobileDesc;
      }
  },
  methods: {
    back() {
      this.$emit("back", "second");
    },
    onEditorChange({ editor, html, text }) {
      this.curMode === 'pc' ? this.newEditForm.metaDesc = html : this.newEditForm.mobileDesc = html;
    },
    submit() {
      this.$emit('next', 'submit',this.newEditForm)
    },
    onEditorBlur() {
      //失去焦点事件
    },
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
      this.$emit("input", this.curMode === 'pc' ? this.newEditForm.metaDesc : this.newEditForm.mobileDesc);
    },

    // 富文本图片上传前
    beforeUpload() {
      // 显示loading动画
      this.quillUpdateImg = true;
    },
    uploadSuccess(res, file) {
      console.log(res, file, "1111111");
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      console.log(quill);
      // 如果上传成功
      if (res.success) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.url为服务器返回的图片地址
        quill.insertEmbed(length, "image", imgPrefix + res.data.fileId);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      // loading动画消失
      this.quillUpdateImg = false;
    },
    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error("图片插入失败");
    },
    //打开图片上传
    uploadClick() {
      var uploadBtn = window.document.getElementById("uploadImg");
      uploadBtn.click();
    },
    //文件状态改变
    handleUploadChange(file, fileList) {
      console.log("------文件状态改变------");
      console.log(file, fileList);
      if (file.status == "success") {
        console.log("------上传成功-----");
        
        this.newEditForm.imageDetail.push(file.response.data.fileId);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.icon-wrap {
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 5px;
  background-color: #666666;
  i {
    color: #ffffff;
    font-size: 30px;
    line-height: 50px;
  }
}
.imgBox {
    margin-right: 10px;
  position: relative;
  width: 50px;
  height: 50px;
  cursor: pointer;
  .imgLight {
    position: absolute;
    width: 50px;
    height: 50px;
    left: 0;
    top: 0;
    background: #000;
    font-size: 50px;
    opacity: 0;
    transition: opacity 0.3s;
  }
}
.imgBox:hover .imgLight {
  opacity: 0.5;
}
.selectWeb {
    display: flex;
    align-items: center;
    margin: 0;
    padding-left: 0;
}
.selectWeb li {
    line-height: 34px;
    border: 1px solid #d7d7d7;
    border-radius: 5px 5px 0 0;
    text-align: center;
    list-style: none;
    width: 100px;
    cursor: pointer;
}
.selectNav {
    background: #f2f2f2;
    font-weight: bold;
}
</style>